package com.kefu.robot.task;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.kefu.robot.model.RobotDoc;
import com.kefu.robot.service.RobotDocService;

import lombok.extern.slf4j.Slf4j;

@Component
@ConditionalOnProperty(prefix = "kefu.task.execute", name = "enabled", havingValue = "true", matchIfMissing = true)
@Slf4j
public class RobotDocTask {

    @Autowired
    private RobotDocService robotDocService;


    @Scheduled(initialDelayString = "#{ T(java.util.concurrent.ThreadLocalRandom).current().nextInt(60*1000) }", fixedRate = 5 * 60 * 1000)
    public void changeStatusByTime() {
        long time = System.currentTimeMillis();
        RobotDoc docModel = new RobotDoc();
        docModel.setTimeMode(1);
        List<RobotDoc> robotDocList = robotDocService.findByModel(docModel);
        for (RobotDoc doc : robotDocList) {
            try {
                RobotDoc updateDoc = new RobotDoc();
                updateDoc.setDocId(doc.getDocId());
                boolean change = false;
                if (doc.getDocStatus() == 0) {
                    if (doc.getStartTime() < time && time < doc.getEndTime()) {
                        updateDoc.setDocStatus(1);
                        change = true;
                    }
                } else if (time < doc.getStartTime() || time > doc.getEndTime()) {
                    updateDoc.setDocStatus(0);
                    change = true;
                }
                if (change) {
                    log.info("docChangeStatus:{},{}", doc, updateDoc);
                    robotDocService.update(updateDoc);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
